package com.hps.spring.cloud.initializrstart.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hps.spring.cloud.initializrstart.service.WeatherDataService;
import com.hps.spring.cloud.initializrstart.vo.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hps
 * @Description:
 * @Date: Created in 11:19 2018/8/29
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static final String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini?";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper mapper;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String url = WEATHER_URL + "citykey=" + cityId;
        return getWeather(url);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String url = WEATHER_URL + "city=" + cityName;
        return getWeather(url);
    }

    private WeatherResponse getWeather(String url) {
        String strBody = null;
        if (stringRedisTemplate.hasKey(url)) {
            strBody = stringRedisTemplate.opsForValue().get(url);
        } else {
            throw new RuntimeException("没有数据");
        }
        if (strBody != null) {
            try {
                return mapper.readValue(strBody, WeatherResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
